# 把Python程序中的数据写入到文件
from day07.Until.studentdemo import StudentInfo


def write_student_info_txt(path, students:dict):
    """
    把students集合的数据写入到指定的路径
    :param path: 指定的路径
    :param students: 集合信息
    :return: 成功失败
    """
    # 定义一个集合存储要写入的文件
    students_str = []

    # 遍历集合
    for index,value in students.items():
        # 定义一个字符串
        str01 = str(index)+ ","
        # 继续遍历
        for i, v in value.items():
            # 拼接字符串
            if i=="result":
                one_line_str = str(v)
                one_line_str = one_line_str[1:len(one_line_str)-1]
                str01 += one_line_str +  "\n"
            else:
                str01 += str(v)+","
        # 把拼接的一行附加到List
        students_str.append(str01)

    # 写入
    try:
        # 打开文件
        with open(path, mode="a", encoding="UTF-8") as fd:
            # 写入
            fd.writelines(students_str)
            # 提示成功
            print("写入成功！")
    except Exception as e:
        print(str(e))


if __name__ == '__main__':
    # 实例化一个对象
    obj01 = StudentInfo()
    # 生成
    obj01.get_student_result_two()
    print(obj01.results02)
    # 定义path
    path = r"E:\Python\Project\BasciProject\student2.csv"
    # 调用
    write_student_info_txt(path, obj01.results02)

